//#region 引入模块
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
// const db = require("./db/db.js");
const cors = require("cors");
const PAQ = require('priority-async-queue');
const paq = new PAQ();
//#endregion
const {makeDir,getfileByUrl,isFileExisted,unlink,fb} = require("./index")

let app = express();
// ajax响应不显示服务端使用框架
app.disable("x-powered-by");

//#region
// 配置静态目录
app.use(express.static(path.join(__dirname, "public")));
// 解析post请求参数
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 配置跨域白名单, 允许携带cookie
app.use(
  cors({
    origin: [
      "127.0.0.1"
    ],
    credentials: true,
  })
);
// 允许跨域
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  // res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials","true");
  res.header("X-Powered-By",' 3.2.1')
  if(req.method === "OPTIONS") res.send(200);/*让options请求快速返回*/
  else  next();
})
// 获取路径
app.get('/path', (req, res) => {
  
  res.send({code:200,data:process.cwd() + '\\ddd'});
});
// 消息队列
app.get('/f', (req, res) => {
  let {name} = req.query
  paq.addTask(() => {
    return paq.sleep(1000).then(() => {
      for (let index = 0; index < 100000; index++) {
        console.log(name);
      }
      
    });
  });
});
// 删除文件
app.get('/unlink', async (req, res) => {
  let {path} = req.query
  let exist = await isFileExisted(path)
  // console.log('是否存在文件',exist);
  if(exist){
    await unlink(path)
  }
  res.send({code:200,data:path + '删除成功'});
});

// 下载文章
app.get('/h', async (req, res) => {
  let params = req.query
  let picUrl = params.url
  let dir = params.dir
  let name = params.name
  let path = dir+'\\'+params.name
  let exist = await isFileExisted(path)
  console.log('是否存在文件',exist);
  if(!exist){
    makeDir(dir)
    getfileByUrl(picUrl, name, dir)
  }
  
  res.send({code:200,data:path});
});
// 发布文章
app.get('/autoSend', (req, res) => {
  let {path,envId,time,article_id} = req.query
  let timestamp = Date.parse(new Date(time).toString());
  let nowTime = Date.parse(new Date().toString());
  console.log({timestamp});
  console.log(timestamp-nowTime);
  console.log(req.query);
  if(time){
    let timestamp = Date.parse(new Date(time).toString());
    let nowTime = Date.parse(new Date().toString());
    let timeEnd = timestamp-nowTime
    paq.addTask(() => {
      return paq.sleep(timeEnd).then(async ()=>{
        var axios = require('axios');
        var FormData = require('form-data');
        var data = new FormData();
        data.append('path', path);
        data.append('envId', envId);
        console.log({path,envId});
        var config = {
          method: 'post',
          url: 'http://127.0.0.1:28089/api/autoSend',
          headers: { 
              'User-Agent': 'Apifox/1.0.0 (https://apifox.com)', 
              'Accept': '*/*', 
              'Host': '127.0.0.1:28089', 
              'Connection': 'keep-alive', 
              'Content-Type': 'multipart/form-data; boundary=--------------------------731258081575450136808080', 
              ...data.getHeaders()
          },
          data : data
        };
  
        let response = await axios(config)
        console.log('发布文章返回结果');
        console.log(JSON.stringify(response.data));
        if(response.data){
          fb(article_id,0,envId)
        }else{
          fb(article_id,1,envId)
        }
      })
    });
    
    return res.send({code:200,data:req.query,msg:'定时任务设置成功'});
  }else{
    var axios = require('axios');
    var FormData = require('form-data');
    var data = new FormData();
    data.append('path', path);
    data.append('envId', envId);

    var config = {
      method: 'post',
      url: 'http://127.0.0.1:28089/api/autoSend',
      headers: { 
          'User-Agent': 'Apifox/1.0.0 (https://apifox.com)', 
          'Accept': '*/*', 
          'Host': '127.0.0.1:28089', 
          'Connection': 'keep-alive', 
          'Content-Type': 'multipart/form-data; boundary=--------------------------731258081575450136808080', 
          ...data.getHeaders()
      },
      data : data
    };

    axios(config)
    .then(function (response) {
      console.log('发布文章返回结果');
      console.log(JSON.stringify(response.data));
      if(response.data){
        res.send({code:200,data:response.data});
      }else{
        res.send({code:201,data:response.data});
      }
      
    })
    .catch(function (error) {
      console.log(error);
      res.send({code:200,data:response.data});
    });
  }
  
  

    
  });

// 发布文章
app.get("/fb", (req, res) => {
  let { path, envId, time } = req.query;

  var axios = require("axios");
  var FormData = require("form-data");
  var data = new FormData();
  data.append("path", path);
  data.append("envId", envId);

  var config = {
    method: "post",
    url: "http://127.0.0.1:28089/api/autoSend",
    headers: {
      "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
      Accept: "*/*",
      Host: "127.0.0.1:28089",
      Connection: "keep-alive",
      "Content-Type":
        "multipart/form-data; boundary=--------------------------731258081575450136808080",
      ...data.getHeaders(),
    },
    data: data,
  };

  axios(config)
    .then(function (response) {
      if (response.data) {
        res.send({ code: 200, data: response.data });
      } else {
        res.send({ code: 201, data: response.data });
      }
    })
    .catch(function (error) {
      console.log(error);
      res.send({ code: 200, data: response.data });
    });
});

// app.all('*', function(req, res, next) {
//   res.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
//   // res.setHeader("Access-Control-Allow-Credentials", true);
//   // res.header("Access-Control-Allow-Headers", "X-Requested-With");
//   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
//   res.header("X-Powered-By",' 3.2.1');
//   res.header("X-Frame-Options", 'deny')
//   res.header("Content-Type", "application/json;charset=utf-8");
//   next();
// });
//#endregion

//#region 配置路由
const testR = require("./routers/test");
app.use("/test", testR);

//#endregion
// db.query("select * from test")
//   .then((res) => {
//     console.log(res);
//   })
//   .catch((err) => {
//     console.log(err);
//   });

app.listen(3001, function () {
  console.log(
    "\x1B[36m%s\x1B[0m",
    "------监听端口 http://127.0.0.1:3001/sys ------"
  );
});
//#region
//#endregion
